﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Configuration;
using SCSService;
using SCS.Core.Models;
using SCS.Core.ViewModels;
using MvcReCaptcha;
using Recaptcha;
using System.IO;
using NLog;
using SCS.Core.Models.ModelsFontend;

namespace SCS.Core.Controllers
{
    public class HomeController:BaseFontendController
    {
        private static readonly Logger Logger = LogManager.GetLogger("register_webshop");

        public ActionResult Index()
        {
            IntPage();
            return View();
        }

        public ActionResult Contact(string result)
        {
            IntPage();
            return View();
        }

        public ActionResult Introduction()
        {
            IntPage();
            return View();
        }

        public ActionResult Media()
        {
            IntPage();
            return View();
        }

        public ActionResult MediaDetail()
        {
            IntPage();
            return View();
        }

        public ActionResult CreateWebshop(int? id)
        {
            IntPage();
            return View();
        }

        public ActionResult SearchBasic(string ProductNameSearch)
        {
            IntPage();
            return View();
        }

        [ChildActionOnly]
        public ActionResult MenuTabArticleStaticCategory()
        {
            int LanguageID = Models.StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter());
            int siteGuid = GetSiteGuid();
            string param = LoadNodeConfigSite(siteGuid, "paramMenuTabArticleStaticCategory");
            List<SCSService.Artilce_Static_Category> listCate = Models.ModelsFontend.ArticaleModel.GetListArticleStaticCategoryByParentIdAndParam(null, LanguageID, GetSiteGuid(), true, param);

            ViewData["MenuTabArticleStaticCategory"] = listCate;

            ///return ket qua la 1 childAction tai 1 folder khac
            return PartialView("../BaseFontend/" + siteGuid + "/MenuTabArticleStaticCategory");

        }

        [ChildActionOnly]
        public ActionResult MenuTabMultiLevelArticleStatic()
        {
            int LanguageID = Models.StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter());
            int siteGuid = GetSiteGuid();
            var viewModel = new ListArticleStaticViewModels2();
            string param = LoadNodeConfigSite(siteGuid, "paramMenuTabMultiLevelArticleStatic");
            string numberArticleInTab = LoadNodeConfigSite(siteGuid, "paramNumberArticleInTab");
            string numberTab = LoadNodeConfigSite(siteGuid, "paramNumberTabArticleStaticCategory2");
            List<SCSService.Artilce_Static_Category> listCate = Models.ModelsFontend.ArticaleModel.GetListArticleStaticCategoryByParentIdAndParam(null, LanguageID, GetSiteGuid(), true, param);

            ViewData["MenuTabMultiLevelArticleStatic"] = listCate;

            int Nofor = 0;
            if (int.Parse(numberTab) > listCate.Count)
            {
                Nofor = listCate.Count;
            }
            else if (int.Parse(numberTab) < listCate.Count)
            {
                Nofor = int.Parse(numberTab);
            }
            else if (int.Parse(numberTab) == listCate.Count)
            {
                Nofor = int.Parse(numberTab);
            }

            for (int i = 0; i < Nofor; i++)
            {
                int currentPage = 1;
                int pageSize = int.Parse(numberArticleInTab);   //Chỉ lấy ra 5 bản ghi cho 1 Article Static Category trên trang chủ (Box left)

                var query = Models.ModelsFontend.ArticaleModel.GetListArticleStaticByCategory(listCate[i].StaticCategoryID, LanguageID, GetSiteGuid(), true).AsQueryable();
                int totalRows = query.Count();

                int totalPages = (int)Math.Ceiling((double)totalRows / (double)pageSize);
                if (totalPages != 1)
                {
                    //paging
                    query = query.Skip(((int)currentPage - 1) * (int)pageSize)
                                    .Take((int)pageSize);
                }

                UpdatePagerViewData(totalPages, totalRows, (int)currentPage, (int)pageSize,null);


                // Set up our ViewModel
                viewModel.NumberTab = int.Parse(numberTab);
                if (i == 0)
                {
                    
                }
                else if (i == 1)
                {
                    viewModel.ArticleStaticItemTab2 = query.ToList();
                    viewModel.ArticleStaticCategoryTab2 = listCate[i].StaticCategoryID != null ? Models.ModelsFontend.ArticaleModel.GetArticleStaticCategory(listCate[i].StaticCategoryID) : null;
                }
                else if (i == 2)
                {
                    viewModel.ArticleStaticItemTab3 = query.ToList();
                    viewModel.ArticleStaticCategoryTab3 = listCate[i].StaticCategoryID != null ? Models.ModelsFontend.ArticaleModel.GetArticleStaticCategory(listCate[i].StaticCategoryID) : null;
                }
               

            }

            ///return ket qua la 1 childAction tai 1 folder khac
            return PartialView("../BaseFontend/" + siteGuid + "/BoxRightHome", viewModel);

        }

        /// <summary>
        /// Đây là control trên trang Home lấy cả list các article Static category và list các article của từng category
        /// paramNumberTabArticleStaticCategory : Là số category có thể hiển thị trên control (max=10)
        /// ParamNumberArticleInTab : là số article trong mỗi category
        /// paramMenuTabArticleStaticCategory : Là param trong ArticleStaticCategory (lấy list Article Static Cateogry theo param này)
        /// các param được đặt trong file config riêng của từng sizeguid (trong thư mục Content/WebsiteTheme/[siteguid])
        /// sonnv tạo ngày 23/12/2011
        /// </summary>
        /// <returns></returns>
        [ChildActionOnly]
        public ActionResult BoxArticleStaticHome()
        {
            int LanguageID = Models.StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter());
            int siteGuid = GetSiteGuid();
            var viewModel = new ListArticleStaticViewModels();

            string param = LoadNodeConfigSite(siteGuid, "paramMenuTabArticleStaticCategory");
            string numberTab = LoadNodeConfigSite(siteGuid, "paramNumberTabArticleStaticCategory");
            string numberArticleInTab = LoadNodeConfigSite(siteGuid, "paramNumberArticleInTab");

            List<SCSService.Artilce_Static_Category> listCate = Models.ModelsFontend.ArticaleModel.GetListArticleStaticCategoryByParentIdAndParam(null, LanguageID, GetSiteGuid(), true, param);

            int Nofor = 0;
            if (int.Parse(numberTab) > listCate.Count)
            {
                Nofor = listCate.Count;
            }
            else if (int.Parse(numberTab) < listCate.Count)
            {
                Nofor = int.Parse(numberTab);
            }
            else if (int.Parse(numberTab) == listCate.Count)
            {
                Nofor = int.Parse(numberTab);
            }

            for (int i = 0; i < Nofor; i++)
            {
                int currentPage = 1;
                int pageSize = int.Parse(numberArticleInTab);   //Chỉ lấy ra 5 bản ghi cho 1 Article Static Category trên trang chủ (Box left)

                var query = Models.ModelsFontend.ArticaleModel.GetListArticleStaticByCategory(listCate[i].StaticCategoryID, LanguageID, GetSiteGuid(),true).AsQueryable();
                int totalRows = query.Count();

                int totalPages = (int)Math.Ceiling((double)totalRows / (double)pageSize);
                if (totalPages != 1)
                {
                    //paging
                    query = query.Skip(((int)currentPage - 1) * (int)pageSize)
                                    .Take((int)pageSize);
                }

                UpdatePagerViewData(totalPages, totalRows, (int)currentPage, (int)pageSize,null);

                
                // Set up our ViewModel
                viewModel.NumberTab = int.Parse(numberTab);
                if(i==0)
                {
                    viewModel.ArticleStaticItemTab1 = query.ToList();
                    viewModel.ArticleStaticCategoryTab1 = listCate[i].StaticCategoryID != null ? Models.ModelsFontend.ArticaleModel.GetArticleStaticCategory(listCate[i].StaticCategoryID) : null;
                }
                else if (i == 1)
                {
                    viewModel.ArticleStaticItemTab2 = query.ToList();
                    viewModel.ArticleStaticCategoryTab2 = listCate[i].StaticCategoryID != null ? Models.ModelsFontend.ArticaleModel.GetArticleStaticCategory(listCate[i].StaticCategoryID) : null;
                }
                else if (i == 2)
                {
                    viewModel.ArticleStaticItemTab3 = query.ToList();
                    viewModel.ArticleStaticCategoryTab3 = listCate[i].StaticCategoryID != null ? Models.ModelsFontend.ArticaleModel.GetArticleStaticCategory(listCate[i].StaticCategoryID) : null;
                }
                else if (i == 3)
                {
                    viewModel.ArticleStaticItemTab4 = query.ToList();
                    viewModel.ArticleStaticCategoryTab4 = listCate[i].StaticCategoryID != null ? Models.ModelsFontend.ArticaleModel.GetArticleStaticCategory(listCate[i].StaticCategoryID) : null;
                }
                else if (i == 4)
                {
                    viewModel.ArticleStaticItemTab5 = query.ToList();
                    viewModel.ArticleStaticCategoryTab5 = listCate[i].StaticCategoryID != null ? Models.ModelsFontend.ArticaleModel.GetArticleStaticCategory(listCate[i].StaticCategoryID) : null;
                }
                else if (i == 5)
                {
                    viewModel.ArticleStaticItemTab6 = query.ToList();
                    viewModel.ArticleStaticCategoryTab6 = listCate[i].StaticCategoryID != null ? Models.ModelsFontend.ArticaleModel.GetArticleStaticCategory(listCate[i].StaticCategoryID) : null;
                }
                else if (i == 7)
                {
                    viewModel.ArticleStaticItemTab8 = query.ToList();
                    viewModel.ArticleStaticCategoryTab8 = listCate[i].StaticCategoryID != null ? Models.ModelsFontend.ArticaleModel.GetArticleStaticCategory(listCate[i].StaticCategoryID) : null;
                }
                else if (i == 9)
                {
                    viewModel.ArticleStaticItemTab10 = query.ToList();
                    viewModel.ArticleStaticCategoryTab10 = listCate[i].StaticCategoryID != null ? Models.ModelsFontend.ArticaleModel.GetArticleStaticCategory(listCate[i].StaticCategoryID) : null;
                }
                
            }
            

            return PartialView("../BaseFontend/" + GetSiteGuid() + "/BoxArticleStaticHome", viewModel);
        }
        /// <summary>
        /// Menu category trên trang Introduction
        /// paramMenuArticleStaticCategoryIntroduction : Là param trong ArticleStaticCategory (lấy list Article Static Cateogry theo param này)
        /// paramTypeMenuCategoryIntroduction : là loại menu article static category (only: chỉ có một danh mục giới thiệu duy nhất. multi: có multi danh mục giới thiệu)
        /// sonnv tạo ngày 03/01/2012
        /// </summary>
        /// <returns></returns>
        [ChildActionOnly]
        public ActionResult MenuArticleStaticCategoryIntroduction()
        {
            int LanguageID = Models.StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter());
            int siteGuid = GetSiteGuid();
            string param = LoadNodeConfigSite(siteGuid, "paramMenuArticleStaticCategoryIntroduction");
            string paramTypeMenuCategoryIntro = LoadNodeConfigSite(siteGuid, "paramTypeMenuCategoryIntroduction");

            List<SCSService.Artilce_Static_Category> listCate = Models.ModelsFontend.ArticaleModel.GetListArticleStaticCategoryByParentIdAndParam(null, LanguageID, GetSiteGuid(), true, param);

            if (paramTypeMenuCategoryIntro != string.Empty && paramTypeMenuCategoryIntro != null)
            {
                if (paramTypeMenuCategoryIntro == "only")
                {
                    var cate = listCate.ToList().FirstOrDefault();
                    if (cate != null)
                    {
                        List<SCSService.Article_Static> listStatic = Models.ModelsFontend.ArticaleModel.GetListArticleStaticByCategory(cate.StaticCategoryID, LanguageID, siteGuid, true);
                        ViewData["MenuArticleStaticCategoryIntroduction"] = listStatic;
                    }
                    else
                        ViewData["MenuArticleStaticCategoryIntroduction"] = null;
                    

                    //Menu là list Article Static trong Article Static Category có param = "MenuIntroduction"
                    //EX: siteGuid 6
                }
                else if (paramTypeMenuCategoryIntro == "multi")
                {
                    ViewData["MenuArticleStaticCategoryIntroduction"] = listCate;

                    //Menu là list Article Static Category có param="MenuIntroduction"
                }
            }
            

            ///return ket qua la 1 childAction tai 1 folder khac
            return PartialView("../BaseFontend/" + siteGuid + "/MenuArticleStaticCategoryIntroduction");

        }

        [ChildActionOnly]
        public ActionResult IntroductionView(int? id)
        {
            int LanguageID = Models.StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter());
            int siteGuid = GetSiteGuid();
            string param = LoadNodeConfigSite(siteGuid, "paramMenuArticleStaticCategoryIntroduction");
            string paramTypeMenuCategoryIntro = LoadNodeConfigSite(siteGuid, "paramTypeMenuCategoryIntroduction");

            List<SCSService.Artilce_Static_Category> listCate = Models.ModelsFontend.ArticaleModel.GetListArticleStaticCategoryByParentIdAndParam(null, LanguageID, GetSiteGuid(), true, param);

            if (paramTypeMenuCategoryIntro != string.Empty && paramTypeMenuCategoryIntro != null)
            {
                if (paramTypeMenuCategoryIntro == "only")
                {
                    var cate = listCate.ToList().FirstOrDefault();
                    List<SCSService.Article_Static> listStatic = Models.ModelsFontend.ArticaleModel.GetListArticleStaticByCategory(cate!=null?cate.StaticCategoryID:0, LanguageID, siteGuid, true);

                    if (id == null)
                    {
                        id = listStatic.FirstOrDefault().StaticID;
                    }

                    //Menu là list Article Static trong Article Static Category có param = "MenuIntroduction"
                    //EX: siteGuid 6
                }
                else if (paramTypeMenuCategoryIntro == "multi")
                {
                    //ViewData["MenuArticleStaticCategoryIntroduction"] = listCate;

                    //Menu là list Article Static Category có param="MenuIntroduction"
                }
            }

            var art = Models.ModelsFontend.ArticaleModel.GetArticleStaticByID((int)id);
            ViewData["ArticleStaticID"] = id;

            return PartialView("../BaseFontend/" + GetSiteGuid() + "/IntroductionView", art);
        }
       
        [ChildActionOnly]
        public ActionResult ContactArticleStaticCategory()
        {
            int LanguageID = Models.StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter());
            int siteGuid = GetSiteGuid();
            string param = LoadNodeConfigSite(siteGuid, "paramContact");
           
            List<SCSService.Artilce_Static_Category> listCate = Models.ModelsFontend.ArticaleModel.GetListArticleStaticCategoryByParentIdAndParam(null, LanguageID, GetSiteGuid(), true, param);

            List<SCSService.Article_Static> listStatic = new List<Article_Static>();
                var cate = listCate.ToList().FirstOrDefault();
                if (cate != null)
                {
                   listStatic = Models.ModelsFontend.ArticaleModel.GetListArticleStaticByCategory(cate.StaticCategoryID, LanguageID, siteGuid, true);
                }
                
                //ViewData["ContactArticleStaticCategory"] = listStatic.FirstOrDefault();
                int id = 0;
                if (listStatic.Count > 0)
                {
                    id = listStatic.FirstOrDefault().StaticID;
                }
                
                //Contact là Article Static trong Article Static Category có param = "Contact"
                //EX: siteGuid 6


                var art = Models.ModelsFontend.ArticaleModel.GetArticleStaticByID((int)id);
            ///return ket qua la 1 childAction tai 1 folder khac
                return PartialView("../BaseFontend/" + siteGuid + "/ContactArticleStaticCategory",art);

        }

        [ChildActionOnly]
        public ActionResult ArticleStaticView(int? id)
        {
            SCSService.Article_Static art=new Article_Static();
            if (id != null)
            {
                art = Models.ModelsFontend.ArticaleModel.GetArticleStaticByID((int)id);
            }
            ViewData["ArticleStaticID"] = id;

            return PartialView("../BaseFontend/" + GetSiteGuid() + "/ArticleStaticView", art);
        }

        [ChildActionOnly]
        [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult ListArticleStaticMedia(int? id)
        {
            int LanguageID = Models.StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter());
            int siteGuid = GetSiteGuid();
            //Id đầu vào là cateId
            int currentPage = 1;
            int pageSize = 5;

            ViewData["currentPage"] = currentPage;
            ViewData["pageSize"] = pageSize;

            if (id == null)
            {
                
                string param = LoadNodeConfigSite(siteGuid, "paramMenuArticleStaticCategoryMedia");
                string paramTypeMenuCategoryIntro = LoadNodeConfigSite(siteGuid, "paramTypeMenuCategoryMedia");

                List<SCSService.Artilce_Static_Category> listCate = Models.ModelsFontend.ArticaleModel.GetListArticleStaticCategoryByParentIdAndParam(null, LanguageID, GetSiteGuid(), true, param);

                id = listCate.FirstOrDefault().StaticCategoryID;
            }

            ViewData["TypeMedia"] = null;
            var StaticCategory = Models.ModelsFontend.ArticaleModel.GetArticleStaticCategory((int)id);
            if (StaticCategory.StaticCategoryParams.Contains("clip"))
            {
                ViewData["TypeMedia"] = "clip";
            }
            else if (StaticCategory.StaticCategoryParams.Contains("album"))
            {
                ViewData["TypeMedia"] = "album";
            }
            else if (StaticCategory.StaticCategoryParams.Contains("document"))
            {
                ViewData["TypeMedia"] = "document";
            }

            return ListArticleStaticMedia(currentPage, pageSize, null, id);
        }

        [ChildActionOnly]
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult ListArticleStaticMedia(int? currentPage, int? pageSize, string gridAction, int? id)
        {
            ViewData["TypeMedia"] = null;
            var StaticCategory = Models.ModelsFontend.ArticaleModel.GetArticleStaticCategory((int)id);
            if (StaticCategory.StaticCategoryParams.Contains("clip"))
            {
                ViewData["TypeMedia"] = "clip";
            }
            else if (StaticCategory.StaticCategoryParams.Contains("album"))
            {
                ViewData["TypeMedia"] = "album";
            }
            else if (StaticCategory.StaticCategoryParams.Contains("document"))
            {
                ViewData["TypeMedia"] = "document";
            }

            int LanguageID = StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter());
            //id đầu vào là typeId
            if (gridAction == "PageSizeChanged")
                currentPage = 1;

            if (currentPage == null && gridAction == "CurrentPageChanged")
            {
                string strCurrentPage = Request.Form.Get("quickPage").Replace(",", "");
                currentPage = int.Parse(strCurrentPage);
            }
            else if (currentPage == null)
            {
                currentPage = 1;
            }

            if (pageSize == null)
            {
                pageSize = 5;
            }

            ViewData["currentPage"] = currentPage;


            var query = Models.ModelsFontend.ArticaleModel.GetListArticleStaticByCategory(id, LanguageID, GetSiteGuid(), true).AsQueryable();
            int totalRows = query.Count();

            int totalPages = (int)Math.Ceiling((double)totalRows / (double)pageSize);
            if (totalPages != 1)
            {
                //paging
                query = query.Skip(((int)currentPage - 1) * (int)pageSize)
                                .Take((int)pageSize);
            }

            UpdatePagerViewData(totalPages, totalRows, (int)currentPage, (int)pageSize,null);

            var result = query.ToList();

            if (query.Count() > 0)
            {

            }

            // Set up our ViewModel
            var viewModel = new ListArticleStaticViewModels
            {
                ArticleStaticItem = result,
                ArticleStaticCategory = id != null ? Models.ModelsFontend.ArticaleModel.GetArticleStaticCategory((int)id) : null
            };

            if (totalRows == 0)
                return PartialView("../BaseFontend/" + GetSiteGuid() + "/ListArticleStaticMedia", new ListArticleStaticViewModels());
            else
                return PartialView("../BaseFontend/" + GetSiteGuid() + "/ListArticleStaticMedia", viewModel);

        }

        /// <summary>
        /// Menu category trên trang Media
        /// paramMenuArticleStaticCategoryMedia: Là param trong ArticleStaticCategory (lấy list Article Static Cateogry theo param này)
        /// paramTypeMenuCategoryMedia : là loại menu article static category (only: chỉ có một danh mục Mdeia duy nhất. multi: có multi danh mục Media)
        /// sonnv tạo ngày 04/02/2012
        /// </summary>
        /// <returns></returns>
        [ChildActionOnly]
        public ActionResult MenuArticleStaticCategoryMedia()
        {
            int LanguageID = Models.StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter());
            int siteGuid = GetSiteGuid();
            string param = LoadNodeConfigSite(siteGuid, "paramMenuArticleStaticCategoryMedia");
            string paramTypeMenuCategoryIntro = LoadNodeConfigSite(siteGuid, "paramTypeMenuCategoryMedia");

            List<SCSService.Artilce_Static_Category> listCate = Models.ModelsFontend.ArticaleModel.GetListArticleStaticCategoryByParentIdAndParam(null, LanguageID, GetSiteGuid(), true, param);

            if (paramTypeMenuCategoryIntro != string.Empty && paramTypeMenuCategoryIntro != null)
            {
                if (paramTypeMenuCategoryIntro == "only")
                {
                    var cate = listCate.ToList().FirstOrDefault();
                    List<SCSService.Article_Static> listStatic = Models.ModelsFontend.ArticaleModel.GetListArticleStaticByCategory(cate.StaticCategoryID, LanguageID, siteGuid, true);
                    ViewData["MenuArticleStaticCategoryMedia"] = listStatic;

                    //Menu là list Article Static trong Article Static Category có param = "MenuMedia"
                    //EX: siteGuid 6
                }
                else if (paramTypeMenuCategoryIntro == "multi")
                {
                    ViewData["MenuArticleStaticCategoryMedia"] = listCate;

                    //Menu là list Article Static Category có param="MenuMedia"
                }
            }


            ///return ket qua la 1 childAction tai 1 folder khac
            return PartialView("../BaseFontend/" + siteGuid + "/MenuArticleStaticCategoryMedia");

        }

        [ChildActionOnly]
        public ActionResult MediaView(int? id,string typeMedia)
        {
            int LanguageID = Models.StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter());
            int siteGuid = GetSiteGuid();
            string param = LoadNodeConfigSite(siteGuid, "paramMenuArticleStaticCategoryMedia");
            string paramTypeMenuCategoryIntro = LoadNodeConfigSite(siteGuid, "paramTypeMenuCategoryMedia");

            List<SCSService.Artilce_Static_Category> listCate = Models.ModelsFontend.ArticaleModel.GetListArticleStaticCategoryByParentIdAndParam(null, LanguageID, GetSiteGuid(), true, param);

            if (paramTypeMenuCategoryIntro != string.Empty && paramTypeMenuCategoryIntro != null)
            {
                if (paramTypeMenuCategoryIntro == "only")
                {
                    var cate = listCate.ToList().FirstOrDefault();
                    List<SCSService.Article_Static> listStatic = Models.ModelsFontend.ArticaleModel.GetListArticleStaticByCategory(cate.StaticCategoryID, LanguageID, siteGuid, true);

                    if (id == null)
                    {
                        id = listStatic.FirstOrDefault().StaticID;
                    }

                    //Menu là list Article Static trong Article Static Category có param = "MenuMedia"
                    //EX: siteGuid 6
                }
                else if (paramTypeMenuCategoryIntro == "multi")
                {
                    //ViewData["MenuArticleStaticCategoryMedia"] = listCate;

                    //Menu là list Article Static Category có param="MenuMedia"
                }
            }

            var art = Models.ModelsFontend.ArticaleModel.GetArticleStaticByID((int)id);
            ViewData["ArticleStaticID"] = id;
            ViewData["TypeMedia"] = typeMedia;

            return PartialView("../BaseFontend/" + GetSiteGuid() + "/MediaView", art);
        }


        

        public JsonResult CheckEmailCreated(string id)
        {
            Logger.Info("check email: " + id);
            if (id != string.Empty && id != null)
            {
                id = id.Replace("-", ".");
            }
            bool re = false;
            int count= Models.ModelsFontend.UserWebModel.GetCountUserByEmail(id);

            if (count > 0)
            {
                re = false;
            }
            else
            {
                re = true;
            }
            Logger.Info("result: " + re);
            return this.Json(re);
        }

        public JsonResult CheckEmailUpdate(string id)
        {
            Logger.Info("check email: " + id);
            if (id != string.Empty && id != null)
            {
                id = id.Replace("-", ".");
            }
            bool re = false;
            int count = Models.ModelsFontend.UserWebModel.GetCountUserByEmail(id);

            if (count > 1)
            {
                re = false;
            }
            else
            {
                re = true;
            }
            Logger.Info("result: " + re);
            return this.Json(re);
        }

        public JsonResult CheckSubdomainCreated(string id)
        {
            Logger.Info("check address subdomain: " + id);
            bool re = false;
            int count = Models.ModelsFontend.UserWebModel.GetCountWebsiteByDomain(id + ".atf.com.vn");

            if (count > 0)
            {
                re = false;
            }
            else
            {
                re = true;
            }
            Logger.Info("result: " + re);
            return this.Json(re);
        }    

        [ChildActionOnly]
        [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult RegistersWebshop(int? id)
        {
            var register = new Models.CollectionFontend.RegisterWebshopCollection();
            register.ProductID = id ?? 0;
            ViewData["ProductID"] = id ?? 0;

            return PartialView("../BaseFontend/" + GetSiteGuid() + "/RegisterWebShop", register);
        }

        [ChildActionOnly]
        [CaptchaValidator]
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult RegistersWebshop(FormCollection collection, bool captchaValid, int? id)
        {

            var register = new Models.CollectionFontend.RegisterWebshopCollection();
            TryUpdateModel(register);
            int cusID = 0;
            int userID = 0;
            int newSiteGuid = 0;                                // new siteguid created
            int sourceSiteGuid = 0;                             // source siteguid copy
            int masterId = 0;
            try
            {

                if (captchaValid)//success captcha
                {
                    if (register.Password.Equals(register.ConfirmPassword))
                    {
                        //Check UserName and Email is Unique
                        if (register.ProductID == 0)
                        {
                            ViewData["Result"] = "Hãy chọn lại theme";
                            return PartialView("../BaseFontend/" + GetSiteGuid() + "/RegisterWebShop", register);
                        }

                        if (Models.ModelsFontend.UserWebModel.GetCountUserByEmail(register.Email) > 0)
                        {
                            ViewData["Result"] = "Email đã được sử dụng";
                            return PartialView("../BaseFontend/" + GetSiteGuid() + "/RegisterWebShop", register);
                        }

                        if (!register.Agree)
                        {
                            ViewData["Result"] = "Bạn cần đồng ý với Quy định sử dụng và chính sách bảo mật của atf";
                            return PartialView("../BaseFontend/" + GetSiteGuid() + "/RegisterWebShop", register);
                        }

                        if (Models.ModelsFontend.UserWebModel.GetCountWebsiteByDomain(register.AddressWebshop) > 0)
                        {
                            ViewData["Result"] = "Địa chỉ website này đã được sử dụng";
                            return PartialView("../BaseFontend/" + GetSiteGuid() + "/RegisterWebShop", register);
                        }

                        SCSService.BaseService baseSvc = new BaseService();

                        //Create new website
                        SCSService.System_Website webshop = new System_Website();
                        webshop.domain = baseSvc.ConvertString2(register.AddressWebshop) + ".atf.com.vn";   //Ten subdomain chi co cac chu cai va dau cham
                        webshop.Description = register.CompanyName + " | " + "proshop";
                        webshop.MainDomain = "atf.com.vn";
                        webshop.Created = DateTime.Now;

                        newSiteGuid = Models.ConfigModel.CreateWebshop(webshop);

                        if (newSiteGuid > 0)
                        {
                            Logger.Info("Đã tạo webshop: " + newSiteGuid);
                            //Create User
                            SCSService.Security_User user = new Security_User();
                            user.UserName = register.Email;
                            user.Email = register.Email;
                            user.Password = baseSvc.EnMD5(register.Password);
                            user.CreateDate = DateTime.Now;
                            user.UserStatus = 1;
                            user.RandomText = baseSvc.RandomString(4, true);
                            user.RoleID = 5;                                                     //admin webshop
                            userID = Models.ModelsFontend.UserWebModel.CreateUser(user);

                            if (userID > 0)
                            {
                                Logger.Info("Đã tạo user: " + userID);
                                //Create Customer
                                SCSService.Customer customer = new Customer();
                                customer.CustomerName = register.FullName;
                                customer.UserID = userID;
                                customer.Email = register.Email;
                                customer.CustomerCode = baseSvc.GetCodeRamdom();
                                customer.Status = 1;
                                customer.CreateDate = DateTime.Now;
                                customer.ActiveDate = DateTime.Now;
                                customer.Balance = 0;
                                customer.CompanyName = register.CompanyName;
                                customer.Phone = register.Phone;

                                cusID = Models.ModelsFontend.UserWebModel.CreateCustomer(customer);

                                //Create User Website
                                SCSService.Security_Website_User webUser = new Security_Website_User();
                                webUser.UserID = userID;
                                webUser.SiteGuid = newSiteGuid;
                                webUser.CreateDate = DateTime.Now;
                                Models.ModelsFontend.UserWebModel.CreateWebsiteUser(webUser);

                                SCSService.Product product = Models.ModelsFontend.ProductModel.GetProductByID(register.ProductID);
                                sourceSiteGuid = int.Parse(product.Features ?? "7");
                                //Features of product is sourceSiteGuid

                                //Create MastePage
                                SCSService.Config_MasterPage master = new Config_MasterPage();
                                master.MasterName = product.ProductCode + ".Master";
                                master.MasterPath = "~/Content/WebsiteTheme/shopmaster/" + product.ProductCode + ".Master";
                                master.MasterDes = "";
                                master.SiteGuid = newSiteGuid;

                                masterId = Models.ConfigModel.CreateMasterPage(master);

                                if (masterId > 0)
                                {
                                    Logger.Info("Đã tạo MasterPage: " + masterId);

                                    //Get List AllModule in source siteguid  (shop mau)
                                    List<Config_Modul> listAllModul = Models.ConfigModel.GetListAllModulBySiteGuid(sourceSiteGuid);
                                    if (listAllModul.Count > 0)
                                    {
                                        //Create System_Website_Module for newSiteguid
                                        foreach (var module in listAllModul)
                                        {
                                            System_Website_Modul swm = new System_Website_Modul();
                                            swm.SiteGuid = newSiteGuid;
                                            swm.ModulID = module.ModulID;
                                            Models.ConfigModel.CreateSystemWebsiteModule(swm);
                                        }
                                        Logger.Info("Đã add list Module :"+listAllModul.Count);
                                    }
                                    else
                                    {
                                        //Không tìm thấy list modul của site nguồn 
                                    }

                                    //Get List All Page in sourceSiteGuid  
                                    List<Config_Page> ListAllPage = Models.ConfigModel.GetListAllPageInWebsite(sourceSiteGuid);
                                    if (ListAllPage.Count > 0)
                                    {

                                        foreach (var page in ListAllPage)
                                        {
                                            //Create Config_Page_Website
                                            Config_Page_Website cpw = new Config_Page_Website();
                                            cpw.SiteGuid = newSiteGuid;
                                            cpw.PageID = page.PageID;
                                            cpw.Status = 1;
                                            Models.ConfigModel.CreateConfigPageWebsite(cpw);

                                            //Create Config_Page_MasterPage
                                            Config_Page_MasterPage cpm = new Config_Page_MasterPage();
                                            cpm.PageID = page.PageID;
                                            cpm.MasterPageID = masterId;
                                            cpm.Status = 1;
                                            Models.ConfigModel.CreateConfigPageMasterPage(cpm);
                                        }

                                        Logger.Info("Đã add ListPage :"+ListAllPage.Count);
                                    }
                                    else
                                    {
                                        //Không tìm thấy list page của site sourceSiteGuid
                                    }

                                    //Get List All Config_Page_Control in siteGuid sourceSiteGuid
                                    List<Config_Page_Control> listControl = Models.ConfigModel.GetListControlInSiteGuid(sourceSiteGuid);
                                    if (listControl.Count > 0)
                                    {
                                        foreach (var control in listControl)
                                        {
                                            //Create Config_Page_control
                                            Config_Page_Control cpc = new Config_Page_Control();
                                            cpc.PageID = control.PageID;
                                            cpc.ControlID = control.ControlID;
                                            cpc.SiteGuid = newSiteGuid;
                                            cpc.ConfigID = null;
                                            cpc.SortOrder = control.SortOrder;
                                            Models.ConfigModel.CreateConfigPageControl(cpc);
                                        }
                                        Logger.Info("Đã add list control: " + listControl.Count);
                                    }
                                    else
                                    {
                                        //Không tìm thấy list control của page sourceSiteGuid
                                    }

                                    //Create New folder for theme

                                    string defaultPath = "C:\\Inetpub\\vhosts\\default\\htdocs\\Content\\WebsiteTheme";
                                    if (Request.Url.Host == "localhost")
                                    {
                                        //Default path on client for test creat shop (this link project in client)
                                        defaultPath = "D:\\project\\atfRTM\\Website\\Content\\WebsiteTheme";
                                        
                                    }
                                    else
                                    {
                                        //Default path on server for theme folder
                                        defaultPath = "C:/Inetpub/vhosts/default/htdocs/Content/WebsiteTheme";
                                    }

                                    if (Directory.Exists(defaultPath))
                                    {
                                        Directory.CreateDirectory(defaultPath + "/" + newSiteGuid);

                                        //Copy file Web.config from siteGuid sourceSiteGuid to newSiteGuid folder
                                        DirectoryInfo dir = new DirectoryInfo(defaultPath + "/" + sourceSiteGuid);
                                        FileInfo[] files = dir.GetFiles();
                                        foreach (FileInfo file in files)
                                        {
                                            if (file.Name == "Web.config")
                                            {

                                                System.IO.File.Copy(defaultPath + "/" + sourceSiteGuid + "/" + file.Name, defaultPath + "/" + newSiteGuid + "/" + "Web.config");
                                                Logger.Info("Đã tạo folder config " + newSiteGuid);
                                                Logger.Info("Đã copy file config ");
                                            }

                                        }

                                    }
                                    else
                                    {
                                        Logger.Info("Đường dẫn thư mục ko đúng:" + "C:/Inetpub/vhosts/default/htdocs/Content/WebsiteTheme");
                                    }


                                    //Create New folder for Views

                                    string defaultPathViews = "C:\\Inetpub\\vhosts\\default\\htdocs\\Content\\WebsiteTheme";
                                    if (Request.Url.Host == "localhost")
                                    {
                                        //Default path on client for test creat shop (this link project in client)
                                        defaultPathViews = "D:\\project\\atfRTM\\Website\\Views\\BaseFontend";
                                    }
                                    else
                                    {
                                        //Default path on server for theme folder
                                        defaultPathViews = "C:/Inetpub/vhosts/default/htdocs/Views/BaseFontend";
                                    }

                                    if (Directory.Exists(defaultPathViews))
                                    {
                                        Directory.CreateDirectory(defaultPathViews + "/" + newSiteGuid);

                                        //Copy Views
                                        DirectoryInfo dir = new DirectoryInfo(defaultPathViews + "/" + sourceSiteGuid);
                                        FileInfo[] files = dir.GetFiles();
                                        foreach (FileInfo file in files)
                                        {

                                            System.IO.File.Copy(defaultPathViews + "/" + sourceSiteGuid + "/" + file.Name, defaultPathViews + "/" + newSiteGuid + "/" + file.Name);

                                        }
                                        Logger.Info("Đã tạo folder Views " + newSiteGuid);
                                        Logger.Info("Đã copy views ");
                                    }
                                    else
                                    {
                                        Logger.Info("Đường dẫn thư mục ko đúng:" + "C:/Inetpub/vhosts/default/htdocs/Views/BaseFontend");
                                    }

                                    //Add language for newSiteguid Default Tiếng việt + English
                                    System_Website_Language swl = new System_Website_Language();
                                    swl.LanguagesID = 1;        //Tiếng việt
                                    swl.SiteGuid = newSiteGuid;
                                    swl.CreateDate = DateTime.Now;

                                    Models.ConfigModel.CreateSystemWebsiteLanguage(swl);

                                    System_Website_Language swl2 = new System_Website_Language();
                                    swl2.LanguagesID = 2;        //Tiếng Anh
                                    swl2.SiteGuid = newSiteGuid;
                                    swl2.CreateDate = DateTime.Now;

                                    Models.ConfigModel.CreateSystemWebsiteLanguage(swl2);

                                    Logger.Info("Đã add Language ");

                                    //Get List menu of sourceSiteGuid
                                    List<Menu> listMenu = Models.ConfigModel.GetListMenuBySiteGuid(sourceSiteGuid, 1);
                                    if (listMenu.Count > 0)
                                    {
                                        foreach (var item in listMenu)
                                        {
                                            Menu me = new Menu();
                                            me.MenuName = item.MenuName;
                                            me.MenuText = item.MenuText;
                                            me.MenuUrl = item.MenuUrl;
                                            me.Images = item.Images;
                                            me.LanguagesID = item.LanguagesID;
                                            me.SiteGuid = newSiteGuid;
                                            me.MenuStatus = item.MenuStatus;
                                            me.PartnerMenuId = item.PartnerMenuId;
                                            me.SortOrder = item.SortOrder;
                                            me.TypeMenuID = item.TypeMenuID;
                                            me.ModuleId = item.ModuleId;

                                            Models.ConfigModel.CreateMenu(me);
                                        }

                                        Logger.Info("Đã add list menu :" +listMenu.Count);

                                    }

                                    //Get List Metadata of sourceSiteGuid
                                    List<Config_Metadata> listMeta = Models.ConfigModel.GetListMetadataBysiteGuid(sourceSiteGuid);
                                    if (listMeta.Count > 0)
                                    {
                                        foreach (var item in listMeta)
                                        {
                                            Config_Metadata metadata = new Config_Metadata();
                                            metadata.MetaTitle = item.MetaTitle;
                                            metadata.MetaKeywords = item.MetaKeywords;
                                            metadata.MetaDescription = item.MetaDescription;
                                            metadata.PageID = item.PageID;
                                            metadata.siteGuid = newSiteGuid;
                                            metadata.Note = item.Note;
                                            metadata.MetaPoweredBy = item.MetaPoweredBy;
                                            metadata.MetaDcCreator = item.MetaDcCreator;
                                            metadata.MetaAuthor = item.MetaAuthor;
                                            metadata.MetaRobots = item.MetaRobots;
                                            metadata.MenuId = item.MenuId;
                                            metadata.Param = item.Param;
                                            metadata.LanguagesID = item.LanguagesID;
                                            metadata.MetaDcctermsModified = item.MetaDcctermsModified;
                                            metadata.MetaDctermsCreated = item.MetaDctermsCreated;
                                            metadata.RevisitAfter = item.RevisitAfter;
                                            metadata.DatePublication = item.DatePublication;
                                            metadata.Homepage = item.Homepage;
                                            metadata.DcLanguage = item.DcLanguage;

                                            Models.ConfigModel.CreateMetadata(metadata);

                                        }

                                        Logger.Info("Đã add list metadata :" + listMeta.Count);
                                    }

                                    //Get List Language_tag in sourceSiteGuid
                                    List<System_Language_Tag> listTag = Models.ConfigModel.GetListTagBySiteGuid(sourceSiteGuid);
                                    if (listTag.Count > 0)
                                    {
                                        foreach (var tag in listTag)
                                        {
                                            //Create New Language_Tag
                                            System_Language_Tag ta = new System_Language_Tag();
                                            ta.TagName = tag.TagName;
                                            ta.TagValue = tag.TagValue;
                                            ta.TagDes = tag.TagDes;
                                            ta.LanguagesID = tag.LanguagesID;
                                            ta.SiteGuid = newSiteGuid;
                                            Models.ConfigModel.CreateSystemLanguageTag(ta);
                                        }

                                        Logger.Info("Đã add list Tag (Transelate) :" + listTag.Count);
                                    }
                                    else
                                    {
                                        //Không tìm thấy list tag của page sourceSiteGuid
                                    }

                                    //Add Type Product for newsiteguid
                                    //Get List type product in siteguid sourceSiteGuid

                                    //Get System_Website_TypeProperties in siteGuid sourceSiteGuid
                                    List<System_Website_TypeProperty> listTypeProperties = Models.ModelsFontend.ProductModel.GetListSystemWebsiteTypePropertiesBysiteGuid(sourceSiteGuid);
                                    if (listTypeProperties.Count > 0)
                                    {
                                        foreach (var item in listTypeProperties)
                                        {
                                            //Add Type Properties for new siteGuid
                                            System_Website_TypeProperty swt = new System_Website_TypeProperty();
                                            swt.SiteGuid = newSiteGuid;
                                            swt.TypePropertiesID = item.TypePropertiesID;
                                            swt.Status = 1;

                                            Models.ModelsFontend.ProductModel.CreateSystemWebsiteTypeProperties(swt);
                                        }

                                        Logger.Info("Đã add list Properties (Thuộc tính) :" + listTypeProperties.Count);
                                    }


                                    // Tiếng Việt
                                    List<Type_Product> listTypeProductVi = GetListTypeProductDropBasic(null, 1, null, null, null, 1, sourceSiteGuid);
                                    if (listTypeProductVi.Count > 0)
                                    {
                                        foreach (var item in listTypeProductVi)
                                        {
                                            Type_Product ty = new Type_Product();
                                            ty.TypeProductName = item.TypeProductName;
                                            ty.TypeProductDes = item.TypeProductDes;
                                            ty.TypeProductImage = item.TypeProductImage;
                                            ty.TypeProductStatus = 1;
                                            ty.LanguagesID = 1;
                                            ty.ParentTypeProductID = item.ParentTypeProductID;
                                            ty.SortOrder = item.SortOrder;
                                            ty.SiteGuid = newSiteGuid;
                                            ty.TypeProductParam = item.TypeProductParam;

                                            Models.StockModel.CreateTypeProduct(ty);
                                        }
                                        Logger.Info("Đã add list Type Product (Vi) :" + listTypeProductVi.Count);
                                    }

                                    // English
                                    List<Type_Product> listTypeProductEn = GetListTypeProductDropBasic(null, 1, null, null, null, 2, sourceSiteGuid);
                                    if (listTypeProductEn.Count > 0)
                                    {
                                        foreach (var item in listTypeProductEn)
                                        {
                                            Type_Product ty = new Type_Product();
                                            ty.TypeProductName = item.TypeProductName;
                                            ty.TypeProductDes = item.TypeProductDes;
                                            ty.TypeProductImage = item.TypeProductImage;
                                            ty.TypeProductStatus = 1;
                                            ty.LanguagesID = 2;
                                            ty.ParentTypeProductID = item.ParentTypeProductID;
                                            ty.SortOrder = item.SortOrder;
                                            ty.SiteGuid = newSiteGuid;
                                            ty.TypeProductParam = item.TypeProductParam;

                                            Models.StockModel.CreateTypeProduct(ty);
                                        }
                                        Logger.Info("Đã add list Type Product (En) :" + listTypeProductEn.Count);
                                    }

                                    //Add List Product for newSiteGuid
                                    //Get List Product Vi siteGuid sourceSiteGuid

                                    // Tiếng Việt
                                    List<Product> listProductVi = Models.ModelsFontend.ProductModel.GetListProductByTypeProduct(null, 1, sourceSiteGuid, 1);
                                    if (listProductVi.Count > 0)
                                    {
                                        foreach (var item in listProductVi)
                                        {
                                            Product pro = new Product();
                                            pro.ProductName = item.ProductName;
                                            pro.ProductCode = item.ProductCode;
                                            pro.ProductDes = item.ProductDes;
                                            pro.Features = item.Features;
                                            pro.Status = 1;
                                            pro.CreateDate = DateTime.Now;
                                            pro.CreateUser = userID;
                                            pro.Images = item.Images;
                                            pro.Title = item.Title;
                                            pro.MetaKeyword = item.MetaKeyword;
                                            pro.MetaDescription = item.MetaDescription;
                                            pro.PriceLast = item.PriceLast;

                                            int proID = Models.StockModel.CreateProduct(pro);

                                            //Get list product Price 
                                            List<Product_Price> oldPrice = Models.ModelsFontend.ProductModel.GetListProductPriceByProductID(item.ProductID, 1, null);
                                            if (oldPrice.Count > 0)
                                            {
                                                foreach (var it in oldPrice)
                                                {
                                                    Product_Price pri = new Product_Price();
                                                    pri.CurrencyID = it.CurrencyID;
                                                    pri.LanguagesID = it.LanguagesID;
                                                    pri.Notes = it.Notes;
                                                    pri.PriceValue = it.PriceValue;
                                                    pri.ProductID = proID;
                                                    pri.Satus = it.Satus;
                                                    pri.StartDate = it.StartDate;
                                                    pri.EndDate = it.EndDate;

                                                    Models.StockModel.CreatePrice(pri);
                                                }
                                            }

                                            //Get product stock 
                                            List<Product_Stock> oldStock = Models.ModelsFontend.ProductModel.GetListProductStockByProductID(item.ProductID);
                                            if (oldStock.Count > 0)
                                            {
                                                foreach (var st in oldStock)
                                                {
                                                    Product_Stock stock = new Product_Stock();
                                                    stock.ProductID = proID;
                                                    stock.Quantity = st.Quantity;
                                                    stock.Status = st.Status;
                                                    stock.StockCode = st.StockCode;
                                                    stock.StockIn = st.StockIn;
                                                    stock.NotesStock = st.NotesStock;
                                                    stock.ModifyDate = st.ModifyDate;

                                                    Models.StockModel.CreateStock(stock);
                                                }
                                            }

                                            //Set List Product_Type_Properties
                                            if (listTypeProperties.Count > 0)
                                            {
                                                foreach (var li in listTypeProperties)
                                                {
                                                    //Add Type Properties for new siteGuid
                                                    Product_Type_Property ptp = new Product_Type_Property();
                                                    ptp.ProductID = proID;
                                                    ptp.TypePropertiesID = li.TypePropertiesID;

                                                    Models.StockModel.CreateProductTypeProperty(ptp);
                                                }
                                            }

                                            Logger.Info("Đã add list Product (Vi) :" + listProductVi.Count);

                                        }
                                    }

                                    // English
                                    List<Product> listProductEn = Models.ModelsFontend.ProductModel.GetListProductByTypeProduct(null, 2, sourceSiteGuid, 1);
                                    if (listProductEn.Count > 0)
                                    {
                                        foreach (var item in listProductEn)
                                        {
                                            Product pro = new Product();
                                            pro.ProductName = item.ProductName;
                                            pro.ProductCode = item.ProductCode;
                                            pro.ProductDes = item.ProductDes;
                                            pro.Features = item.Features;
                                            pro.Status = 1;
                                            pro.CreateDate = DateTime.Now;
                                            pro.CreateUser = userID;
                                            pro.Images = item.Images;
                                            pro.Title = item.Title;
                                            pro.MetaKeyword = item.MetaKeyword;
                                            pro.MetaDescription = item.MetaDescription;
                                            pro.PriceLast = item.PriceLast;

                                            int proID = Models.StockModel.CreateProduct(pro);

                                            //Get list product Price 
                                            List<Product_Price> oldPrice = Models.ModelsFontend.ProductModel.GetListProductPriceByProductID(item.ProductID, 2, null);
                                            if (oldPrice.Count > 0)
                                            {
                                                foreach (var it in oldPrice)
                                                {
                                                    Product_Price pri = new Product_Price();
                                                    pri.CurrencyID = it.CurrencyID;
                                                    pri.LanguagesID = it.LanguagesID;
                                                    pri.Notes = it.Notes;
                                                    pri.PriceValue = it.PriceValue;
                                                    pri.ProductID = proID;
                                                    pri.Satus = it.Satus;
                                                    pri.StartDate = it.StartDate;
                                                    pri.EndDate = it.EndDate;

                                                    Models.StockModel.CreatePrice(pri);
                                                }
                                            }

                                            //Get product stock 
                                            List<Product_Stock> oldStock = Models.ModelsFontend.ProductModel.GetListProductStockByProductID(item.ProductID);
                                            if (oldStock.Count > 0)
                                            {
                                                foreach (var st in oldStock)
                                                {
                                                    Product_Stock stock = new Product_Stock();
                                                    stock.ProductID = proID;
                                                    stock.Quantity = st.Quantity;
                                                    stock.Status = st.Status;
                                                    stock.StockCode = st.StockCode;
                                                    stock.StockIn = st.StockIn;
                                                    stock.NotesStock = st.NotesStock;
                                                    stock.ModifyDate = st.ModifyDate;

                                                    Models.StockModel.CreateStock(stock);
                                                }
                                            }

                                            //Set List Product_Type_Properties
                                            if (listTypeProperties.Count > 0)
                                            {
                                                foreach (var li in listTypeProperties)
                                                {
                                                    //Add Type Properties for new siteGuid
                                                    Product_Type_Property ptp = new Product_Type_Property();
                                                    ptp.ProductID = proID;
                                                    ptp.TypePropertiesID = li.TypePropertiesID;

                                                    Models.StockModel.CreateProductTypeProperty(ptp);
                                                }
                                            }

                                            Logger.Info("Đã add list Product (En) :" + listProductEn.Count);
                                        }
                                    }

                                    //Create Type_Product_Manage for Product in newSiteGuid
                                    //Get List TypeProduct in newsiteGuid
                                    List<Type_Product> listTypeVi = Models.StockModel.GetListTypeProductByParentId(null, 1, newSiteGuid);
                                    foreach (var pro in listProductVi)
                                    {
                                        foreach (var type in listTypeVi)
                                        {
                                            Type_Product_Manage newMana = new Type_Product_Manage();
                                            newMana.TypeProductID = type.TypeProductID;
                                            newMana.ProductID = pro.ProductID;
                                            newMana.Status = 1;

                                            Models.StockModel.CreateManageTypeProduct(newMana);
                                        }
                                    }

                                    List<Type_Product> listTypeEn = Models.StockModel.GetListTypeProductByParentId(null, 2, newSiteGuid);
                                    foreach (var pro in listProductEn)
                                    {
                                        foreach (var type in listTypeEn)
                                        {
                                            Type_Product_Manage newMana = new Type_Product_Manage();
                                            newMana.TypeProductID = type.TypeProductID;
                                            newMana.ProductID = pro.ProductID;
                                            newMana.Status = 1;

                                            Models.StockModel.CreateManageTypeProduct(newMana);
                                        }
                                    }


                                    //Get List Artilce_Static_Categories in sourceSiteGuid
                                    List<Artilce_Static_Category> listArticleStaticCategory = Models.ArticaleMasterModel.GetListStaticArticleCategoryBySiteGuid(sourceSiteGuid);
                                    if (listArticleStaticCategory.Count > 0)
                                    {
                                        foreach (var li in listArticleStaticCategory)
                                        {
                                            //Add Article static Category for new siteGuid
                                            Artilce_Static_Category ast = new Artilce_Static_Category();
                                           
                                            ast.StaticCategoryName = li.StaticCategoryName;
                                            ast.StaticCategoryAlias = li.StaticCategoryAlias;
                                            ast.StaticCategoryAccess = li.StaticCategoryAccess;
                                            ast.StaticCategoryParams = li.StaticCategoryParams;
                                            ast.StaticCategoryOrder = li.StaticCategoryOrder;
                                            ast.StaticCategoryActive = li.StaticCategoryActive;
                                            ast.StaticCategoryUrl = li.StaticCategoryUrl;
                                            ast.LanguagesID = li.LanguagesID;
                                            ast.StaticCategoryParentID = li.StaticCategoryParentID;
                                            ast.Images = li.Images;
                                            ast.SiteGuid = newSiteGuid;

                                            int idast= Models.ArticaleMasterModel.CreateStaticArticleCategory(ast);

                                            if (idast > 0)
                                            {
                                                List<Article_Static> listArtStatic = Models.ArticaleMasterModel.GetListArticleStaticByCategoryIdAndSiteGuid(li.StaticCategoryID, sourceSiteGuid);
                                                foreach (var liArtSt in listArtStatic)
                                                {
                                                    Article_Static artSt = new Article_Static();
                                                    artSt.StaticName = liArtSt.StaticName;
                                                    artSt.StaticIntroText = liArtSt.StaticIntroText;
                                                    artSt.StaticContent = liArtSt.StaticContent;
                                                    artSt.Url = liArtSt.Url;
                                                    artSt.Alias = liArtSt.Alias;
                                                    artSt.Active = liArtSt.Active;
                                                    artSt.Images = liArtSt.Images;

                                                    int idartSt = Models.ArticaleMasterModel.CreateArticleStatic(artSt);

                                                    if (idartSt > 0)
                                                    {
                                                        //Create Article Static Fontend 
                                                        Article_Static_Frontpage asf = new Article_Static_Frontpage();
                                                        asf.StaticCategoryID = idast;
                                                        asf.StaticID = idartSt;

                                                        Models.ArticaleMasterModel.CreateArticleStaticFrontpage(asf);
                                                    }
                                                    
                                                }
                                            }

                                            
                                            
                                        }
                                        Logger.Info("Đã add list Article Static :" + listArticleStaticCategory.Count);
                                    }

                                    //Get List Article Category in sourceSite
                                    List<Article_Category> listArtCate = Models.ArticaleMasterModel.GetListArticaleCategoryBySiteGuid(sourceSiteGuid);
                                    if (listArtCate.Count > 0)
                                    {
                                        foreach (var item in listArtCate)
                                        {
                                            Article_Category ac = new Article_Category();
                                            ac.CategoriesName = item.CategoriesName;
                                            ac.CategoriesAlias = item.CategoriesAlias;
                                            ac.CategoriesAccess = item.CategoriesAccess;
                                            ac.CategoriesParams = item.CategoriesParams;
                                            ac.CategoriesOrdering = item.CategoriesOrdering;
                                            ac.CategoriesActive = item.CategoriesActive;
                                            ac.CategoriesUrl = item.CategoriesUrl;
                                            ac.LanguagesID = item.LanguagesID;
                                            ac.CategoriesParentID = item.CategoriesParentID;
                                            ac.Images = item.Images;
                                            ac.SiteGuid = newSiteGuid;

                                            int idac= Models.ArticaleMasterModel.CreateArticleCategory(ac);
                                            if (idac > 0)
                                            {
                                                List<Article> listArticle = Models.ArticaleMasterModel.GetListArticleByCategoryAndSiteguid(item.CategoriesID, sourceSiteGuid);
                                                if (listArticle.Count > 0)
                                                {
                                                    foreach (var liItem in listArticle)
                                                    {
                                                        Article article = new Article();
                                                        article.Title = liItem.Title;
                                                        article.Alias = liItem.Alias;
                                                        article.IntroText = liItem.IntroText;
                                                        article.FullText = liItem.FullText;
                                                        article.Images = liItem.Images;
                                                        article.Created = DateTime.Now;
                                                        article.CreatedBy = userID;
                                                        article.Url = liItem.Url;
                                                        article.Version = liItem.Version;
                                                        article.Hits = liItem.Hits;
                                                        article.Ordering = liItem.Ordering;
                                                        article.Active = liItem.Active;
                                                        article.MetaKey = liItem.MetaKey;
                                                        article.MetaDesc = liItem.MetaDesc;
                                                        article.MetaData = liItem.MetaData;
                                                        article.Attribs = liItem.Attribs;
                                                        article.Access = liItem.Access;
                                                        article.CheckedOut = liItem.CheckedOut;
                                                        article.CheckedOutTime = liItem.CheckedOutTime;
                                                        article.PublicUp = liItem.PublicUp;
                                                        article.PublicDown = liItem.PublicDown;
                                                        article.Tags = liItem.Tags;
                                                        article.Related = liItem.Related;

                                                        int idArticle = Models.ArticaleMasterModel.CreateArticle(article);

                                                        if (idArticle > 0)
                                                        {
                                                            //Create Article Fontend 
                                                            Article_Frontpage af = new Article_Frontpage();
                                                            af.ArticleID = idArticle;
                                                            af.CategoriesID = idac;

                                                            Models.ArticaleMasterModel.CreateArticleFrontpage(af);
                                                        }
                                                    }
                                                }
                                                Logger.Info("Đã add list Article :" + listArticle.Count);
                                            }
                                        }

                                        
                                    }
                                    

                                    //

                                    //End create shop 
                                    if (Request.Url.Host == "localhost")
                                    {
                                        ViewData["redirectStr"] = "/" + newSiteGuid + "/vi/Home/Index";
                                    }
                                    else
                                    {
                                        ViewData["redirectStr"] = baseSvc.ConvertString2(register.AddressWebshop) + ".atf.com.vn" + "/vi/Home/Index";
                                    }

                                    //Send Email Information master admin
                                    string content="<table width='100%' bgcolor='#f2f2f2' border='0' cellspacing='0' cellpadding='0' align='center'>";
			                           content+=" <!-- TITLE BAR --> ";
                                       content+=" <tr>";
            	                       content+=" <td></td>";
                                       content+=" </tr>"; 
                                       content+=" <tr>";
                                       content += "     <td align='center'><img src='http://proshop.atf.com.vn/ThemeExtends/tememail/images/header.jpg' alt='Title' width='692' height='164' border='0'/></td>";
			                           content+=" </tr>";
                                       content+=" <tr><td>";
                                       content+=" <table width='668' bgcolor='#f9f9f9' border='0' cellspacing='0' cellpadding='0' align='center'>";
                                       content+=" <!-- DATE -->";  
                                       content+=" <tr>";
                                       content+="     <td colspan='3'><center><h2>Thông báo khởi tạo Website thành công</h2></center></td>";
			                           content+=" </tr>";
                                       content+=" <!-- MAIN CONTENT --> ";
			                           content+=" <tr>";
                                       content+=" <td width='48'></td>";
				                       content+="     <td align='center'>";
					                   content+="         <table width='572' border='0' cellspacing='0' cellpadding='0'>";
                    	               content+="             <tr>";
                                       content += "                 <td><img src='http://proshop.atf.com.vn/'" + product.Images + "' alt='Main' width='572' height='258' border='0' /></td>";
                    	               content+="             </tr>";
                                       content+="             <tr><td>";
                                       content+="             <table width='550' border='0' cellspacing='0' cellpadding='0' align='center'>";
						               content+="             <tr>";
						               content+="             <tr><td colspan='2'><br /></td></tr>";
							           content+="                 <td colspan='2'>";
							           content+="                     <h3>Chào : "+register.FullName+"</h3>";
                                       content += "                     <p>Chúc mừng bạn đã khởi tạo thành công website <a href='" + ViewData["redirectStr"].ToString() + "'>" + baseSvc.ConvertString2(register.AddressWebshop)+".atf.com.vn" + "</a> trên hệ thống atf Proshop</p>";
                                       content+="                     <p>Thông tin về Website của bạn :</p>";
                                       content += "                     <p>Tên miền sử dụng : " + "http://" + baseSvc.ConvertString2(register.AddressWebshop) + ".atf.com.vn" + "</p>";
                                       content+="                     <p>Ngày khởi tạo : "+DateTime.Now.ToShortDateString()+"</p>";
                                       content+="                     <p>Ngày hết hạn : "+DateTime.Now.AddDays(15).ToShortDateString()+"</p>";
                                       content+="                     <p>Tên công ty/Cửa hàng : "+register.CompanyName+"</p>";
                                       content+="                     <p>Tài khoản quản trị : "+register.Email+"</p>";
                                       content+="                     <p>Mật khẩu tài khoản quản trị : "+register.Password+"</p>";
                                       content+="                     <p>Hệ thống quản trị : Bạn truy cập vào địa chỉ sau <a href='http://atfmaster.com'>http://atfmaster.com/</a>";
                                       content+="                     <p>Để sử dụng domain riêng. Bạn truy cập vào hệ thống quản trị theo địa chỉ trên và thực hiện 2 thao tác:</p>";
                                       content+="                     <p>- Cấu hình trỏ tên miền về địa chỉ IP : 112.213.94.225</p>";
                                       content+="                     <p>- Cấu hình website : 'Advantage Setting > Setting domain' để thêm tên miền bạn định sử dụng</p>";
                                       content+="                     <p>Chúc mừng bạn đến với hệ thống atf proshop.</p>";
                                       content+="                 </td>";
						               content+="             </tr>";
                                       content+="             <tr><td colspan='2'><br /></td></tr>";
                                       content+="             <!-- LOWER CONTENT -->";  
                                       content+="             </table>";    
						               content+="             </td></tr>";
                                       content+="             </table>";
				                       content+="     </td>";
                                       content+="     <td width='48'></td>";
			                           content+=" </tr>";
                                       content+=" </table>";
                                       content+=" </td>";
                                       content+=" </tr>";
                                       content+=" <!-- FOOTER -->"; 
                                       content+=" <tr>";
                                       content += "     <td align='center'><img src='http://proshop.atf.com.vn/ThemeExtends/tememail/images/footer.jpg' alt='Footer' width='692' height='120' border='0' /></td>";
			                           content+=" </tr>";
                                       content+=" <tr>";
            	                       content+="     <td align='center'>";
               
            	                       content+="     </td>";
                                       content+=" </tr>";
		                            content+="</table>";
                                    baseSvc.SendMailMessageforRegisterWebshop(register.Email, null, content, null, null, null, null, null);

                                    Logger.Info("Đã send email to new user :" + register.Email);
                                }

                            }
                        }
                        else
                        {

                        }



                    }
                    else
                    {
                        ViewData["Result"] = "Password must same as Confirm Password";
                    }
                }
                else
                {
                    ViewData["Result"] = "Code Invalid!";
                    return PartialView("../BaseFontend/" + GetSiteGuid() + "/RegisterWebShop", register);
                }

            }
            catch
            {
                return PartialView("../BaseFontend/" + GetSiteGuid() + "/RegisterWebShop", register);
            }
            Logger.Info("Hoàn thành tạo website :" + newSiteGuid);
            Logger.Info("Địa chỉ website :" + ViewData["redirectStr"]);
            return PartialView("../Commont/ResultRegisterWebShop");
        }

        

        [ChildActionOnly]
        [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult ListProductSearchBasic(string ProductNameSearch)
        {
            int currentPage = 1;
            int pageSize = 9;

            ViewData["typeList"] = "list";
            ViewData["currentPage"] = currentPage;
            ViewData["pageSize"] = pageSize;
            ViewData["searchAction"] = "";

            int siteGuid = GetSiteGuid();
            return ListProductSearchBasic(ProductNameSearch, currentPage, pageSize, null, "list", false);
            // return PartialView("../BaseFontend/" + siteGuid + "/SearchBasic");
        }

        [ChildActionOnly]
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult ListProductSearchBasic(string ProductNameSearch, int? currentPage, int? pageSize, string gridAction, string typeList, bool? searchAction)
        {
            int LanguageID = StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter());
            int siteGuid = GetSiteGuid();

            if (typeList == null || typeList == string.Empty)
            {
                ViewData["typeList"] = "list";
                typeList = "list";
            }
            else
            {
                ViewData["typeList"] = typeList;
            }

            if (searchAction == true || ProductNameSearch!=null)
            {
                ViewData["searchAction"] = "view";
            }
            else
                ViewData["searchAction"] = "";



            if (gridAction == "PageSizeChanged")
                currentPage = 1;

            if (currentPage == null && gridAction == "CurrentPageChanged")
            {
                string strCurrentPage = Request.Form.Get("quickPage").Replace(",", "");
                currentPage = int.Parse(strCurrentPage);
            }
            else if (currentPage == null)
            {
                currentPage = 1;
            }

            if (pageSize == null)
            {
                pageSize = 9;
            }

            ViewData["currentPage"] = currentPage;

            var query = Models.ModelsFontend.ProductModel.GetListProductSearchBasic(ProductNameSearch, LanguageID, siteGuid).AsQueryable();
            int totalRows = query.Count();

            int totalPages = (int)Math.Ceiling((double)totalRows / (double)pageSize);
            if (totalPages != 1)
            {
                //paging
                query = query.Skip(((int)currentPage - 1) * (int)pageSize)
                                .Take((int)pageSize);
            }

            UpdatePagerViewData(totalPages, totalRows, (int)currentPage, (int)pageSize, null);

            var result = query.ToList();
            var cart = ShoppingCart.GetCart(this.HttpContext);
            var list = cart.GetListCartItemByCartID();
            ShoppingCart shopcart = new ShoppingCart();

            ViewData["cart"] = list;
            // Set up our ViewModel
            var viewModel = new ListProductViewModels
            {
                ProductItem = result,
                TypeProduct = null,
                ProductNameSearch = ProductNameSearch,
                ProductCodeSearch = null
            };

            //if (totalRows == 0)
            //    return PartialView("../BaseFontend/" + GetSiteGuid() + "/ListProducts", new List<SCSService.Product>());
            //else
            return PartialView("../BaseFontend/" + GetSiteGuid() + "/SearchBasic", viewModel);
        }

        
    }
}
